package com.cxh.rmsq.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.cxh.rmsq.common.Constant;
import com.cxh.rmsq.common.ErrorCode;
import com.cxh.rmsq.common.IntentExtra;
import com.cxh.rmsq.common.ResultCallback;
import com.cxh.rmsq.event.EventMessage;
import com.cxh.rmsq.event.LiveEventBusCode;
import com.cxh.rmsq.im.IMManager;
import com.cxh.rmsq.model.LoginResult;
import com.cxh.rmsq.model.Resource;
import com.cxh.rmsq.model.Resource2;
import com.cxh.rmsq.model.Status;
import com.cxh.rmsq.model.UserCacheInfo;
import com.cxh.rmsq.net.newNet.BaseResultEntity;
import com.cxh.rmsq.net.newNet.ProjectViewModel;
import com.cxh.rmsq.net.newNet.TreasureViewModel;
import com.cxh.rmsq.ui.activity.MainActivity;
import com.cxh.rmsq.ui.activity.NoVerificationCodeActivity;
import com.cxh.rmsq.ui.activity.WebViewActivity;
import com.cxh.rmsq.ui.activity.self.ForgetPwdActivity;
import com.cxh.rmsq.ui.activity.self.SexActivity;
import com.cxh.rmsq.ui.activity.self.WeChatBindPhoneActivity;
import com.cxh.rmsq.utils.RegexUtils;
import com.cxh.rmsq.utils.ToastUtils;
import com.cxh.rmsq.utils.log.SLog;
import com.cxh.rmsq.viewmodel.LoginViewModel;

import com.cxh.rmsq.R;

import com.cxh.rmsq.ui.dialog.SecurityKickOutDialog;
import com.cxh.rmsq.ui.widget.ClearWriteEditText;
import com.cxh.rmsq.wx.WXManager;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mm.opensdk.utils.Log;


import java.util.HashMap;

import io.rong.callkit.util.SPUtils;
import io.rong.imlib.common.ExecutorFactory;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;

public class LoginNewFragment extends BaseFragment {
    private ClearWriteEditText phoneNumberEdit;
    private ClearWriteEditText verifyCodeEdit, inputPwd;

    private LoginViewModel loginViewModel;
    private TextView sendCodeBtn;
    private ImageView ivClean, ivWechatLogin;
    private CheckBox checkbox;
    private LinearLayout llCode, llPwd;
    private TextView tvCodePsw, tvPsw, tvNoCode, tvForgetPwd;
    private boolean isRequestVerifyCode = false; // 是否请求成功验证码
    private OnLoginListener loginListener;
    private int loginType = 1;//验证码登录
    private TreasureViewModel viewModel;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_login_new;
    }

    @Override
    protected void onInitView(Bundle savedInstanceState, Intent intent) {

        phoneNumberEdit = findView(R.id.et_phone);
        verifyCodeEdit = findView(R.id.et_code);
        inputPwd = findView(R.id.et_pwd);

        findView(R.id.tv_login, true);
        ivClean = findView(R.id.iv_clean, true);
        llCode = findView(R.id.ll_code);
        llPwd = findView(R.id.ll_pwd);
        tvNoCode = findView(R.id.tv_no_code, true);
        tvPsw = findView(R.id.tv_psw, true);
        tvCodePsw = findView(R.id.tv_code_psw, true);
        tvForgetPwd = findView(R.id.tv_forget_pwd, true);
        checkbox = findView(R.id.checkbox, true);
        ivWechatLogin = findView(R.id.iv_wechat_login, true);
        sendCodeBtn = findView(R.id.tv_send_code, true);
        sendCodeBtn.setEnabled(false);
        initRegistrationTerms();

        phoneNumberEdit.addTextChangedListener(
                new TextWatcher() {
                    @Override
                    public void beforeTextChanged(
                            CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (s.length() == 11) {
                            phoneNumberEdit.clearFocus();
                            InputMethodManager imm =
                                    (InputMethodManager)
                                            getContext()
                                                    .getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(phoneNumberEdit.getWindowToken(), 0);
                        }
                        if (s.length() > 0 && !isRequestVerifyCode) {
                            sendCodeBtn.setEnabled(true);
                        } else {
                            sendCodeBtn.setEnabled(false);
                        }
                        if (!TextUtils.isEmpty(phoneNumberEdit.getText().toString().trim())) {
                            ivClean.setVisibility(View.VISIBLE);
                        } else {
                            ivClean.setVisibility(View.GONE);
                        }


                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                    }
                });

        viewModel = ViewModelProviders.of(this).get(TreasureViewModel.class);
        LiveEventBus.get(LiveEventBusCode.TEST_COMMENT_VISIBLE, String.class)
                .observe(getViewLifecycleOwner(), code -> {
                    Log.e("wxlogin", code);
                    if (Constant.isWxLogin) {
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("type", 1);//1 android 2 ios
                        map.put("openCode", code);
                        viewModel.loginThird(map, new Function1<BaseResultEntity<LoginResult>, Unit>() {
                            @Override
                            public Unit invoke(BaseResultEntity<LoginResult> result) {
                                if (result.getCode() == 200) {
                                    if (TextUtils.isEmpty(result.getData().getIsBd())) {//直接登录
                                        LoginResult loginResult = result.getData();
                                        SPUtils.put(requireContext(), "accessToken", loginResult.accessToken);
                                        com.blankj.utilcode.util.SPUtils.getInstance().put("accessToken", loginResult.accessToken);
                                        SPUtils.put(requireContext(), "rewRegistration", loginResult.rewRegistration);
                                        SPUtils.put(requireContext(),"loginMob",loginResult.mobile);

                                        Log.e("accessToken", SPUtils.get(requireContext(), "accessToken", "").toString());
                                        if (loginResult != null) {
                                            IMManager.getInstance().connectIM(
                                                    loginResult.rongCloudToken,
                                                    true,
                                                    false,
                                                    new ResultCallback<String>() {
                                                        @Override
                                                        public void onSuccess(String s) {
                                                            // if ("1".equals(SPUtils.get(getActivity(), "rewRegistration", ""))) {
//                                                        toSex();
//                                                    } else {
                                                            toMain(s);
                                                            showToast(R.string.seal_login_toast_success);
//                                                    }
                                                        }

                                                        @Override
                                                        public void onFail(int errorCode) {
                                                            showToast("登录失败");
                                                        }
                                                    });
                                        }
                                    } else {
                                        //去绑定手机号
                                        requireActivity().startActivity(new Intent(getActivity(), WeChatBindPhoneActivity.class)
                                                .putExtra("code", result.getData().getOpenid()));
                                    }
                                }
                                return null;
                            }
                        });
                    }
                });

    }

    @Override
    protected void onInitViewModel() {
        loginViewModel = ViewModelProviders.of(getActivity()).get(LoginViewModel.class);
        loginViewModel
                .getLoginResult()
                .observe(
                        this,
                        new Observer<Resource2<String>>() {
                            @Override
                            public void onChanged(Resource2<String> resource) {
                                if (resource.status == Status.SUCCESS) {
                                    IMManager.getInstance().resetAfterLogin();

                                    dismissLoadingDialog(
                                            new Runnable() {
                                                @Override
                                                public void run() {
                                                    assert resource.data != null;
//                                                    if ("1".equals(SPUtils.get(getActivity(), "rewRegistration", ""))) {
//                                                        toSex();
//                                                    } else {
                                                    toMain(resource.data);
                                                    showToast(R.string.seal_login_toast_success);
//                                                    }
                                                }
                                            });
                                } else if (resource.status == Status.LOADING) {
                                    showLoadingDialog(R.string.seal_loading_dialog_logining);
                                } else if (resource.status == Status.ERROR) {
                                    int code = resource.code;
                                    SLog.d(
                                            "ss_register_and_login",
                                            "register and login failed = " + code);
                                    dismissLoadingDialog(
                                            new Runnable() {
                                                @Override
                                                public void run() {
                                                    showToast(resource.msg);
                                                    if (code == ErrorCode.USER_BLOCKED.getCode()) {
                                                        showSecurityKickOutDialog();
                                                    }
                                                    if (code == 500) {
                                                        showToast("系统异常");
                                                    }
                                                    if (code == 1002014000) {
                                                        showToast("验证码不存在");
                                                    }
                                                    if (code == 1002014001) {
                                                        showToast("验证码已过期");
                                                    }
                                                    if (code == 1002014002) {
                                                        showToast("验证码已使用");
                                                    }
                                                    if (code == 1002014000) {
                                                        showToast("验证码不存在");
                                                    }
                                                }
                                            });
                                }
                            }
                        });

        loginViewModel
                .getLoginPwdResult()
                .observe(
                        this,
                        new Observer<Resource2<String>>() {
                            @Override
                            public void onChanged(Resource2<String> resource) {
                                if (resource.status == Status.SUCCESS) {
                                    IMManager.getInstance().resetAfterLogin();

                                    dismissLoadingDialog(
                                            new Runnable() {
                                                @Override
                                                public void run() {
                                                    assert resource.data != null;
//                                                    if ("1".equals(SPUtils.get(getActivity(), "rewRegistration", ""))) {
//                                                        toSex();
//                                                    } else {
                                                    toMain(resource.data);
                                                    showToast(R.string.seal_login_toast_success);
//                                                    }
                                                }
                                            });
                                } else if (resource.status == Status.LOADING) {
                                    showLoadingDialog(R.string.seal_loading_dialog_logining);
                                } else if (resource.status == Status.ERROR) {
                                    int code = resource.code;
                                    SLog.d(
                                            "ss_register_and_login",
                                            "register and login failed = " + code);
                                    dismissLoadingDialog(
                                            new Runnable() {
                                                @Override
                                                public void run() {
                                                    showToast(resource.msg);
                                                    if (code == ErrorCode.USER_BLOCKED.getCode()) {
                                                        showSecurityKickOutDialog();
                                                    }
                                                    if (code == 1004003000) {
                                                        showToast("登录失败，账号密码不正确");
                                                    }
                                                    if (code == 1004003001) {
                                                        showToast("登录失败，账号被封禁");
                                                    }
                                                    if (code == 500) {
                                                        showToast("系统异常");
                                                    }
                                                }
                                            });
                                }
                            }
                        });

        loginViewModel
                .getLastLoginUserCache()
                .observe(
                        this,
                        new Observer<UserCacheInfo>() {
                            @Override
                            public void onChanged(UserCacheInfo userInfo) {
                                phoneNumberEdit.setText(userInfo.getPhoneNumber());
                                String region = "86";

//                                verifyCodeEdit.setText(userInfo.getPassword());
                            }
                        });

        loginViewModel
                .getSendCodeState()
                .observe(
                        this,
                        new Observer<Resource<String>>() {
                            @Override
                            public void onChanged(Resource<String> resource) {
                                // 提示
                                if (resource.status == Status.SUCCESS) {
                                    showToast(R.string.seal_login_toast_send_code_success);
                                } else if (resource.status == Status.LOADING) {

                                } else {
                                    showToast(resource.message);
                                    sendCodeBtn.setEnabled(true);
                                }
                            }
                        });

        // 等待接受验证码倒计时， 并刷新及时按钮的刷新
        loginViewModel
                .getCodeCountDown()
                .observe(
                        this,
                        new Observer<Integer>() {
                            @Override
                            public void onChanged(Integer integer) {
                                if (integer > 0) {
                                    sendCodeBtn.setText(integer + "s");
                                    isRequestVerifyCode = true;
                                } else {
                                    // 当计时结束时， 恢复按钮的状态
                                    sendCodeBtn.setEnabled(true);
                                    sendCodeBtn.setText(R.string.seal_login_send_code);
                                    isRequestVerifyCode = false;
                                }
                            }
                        });
    }


    /**
     * 显示数美踢出对话框
     */
    private void showSecurityKickOutDialog() {
        SecurityKickOutDialog dialog = new SecurityKickOutDialog();
        dialog.show(getActivity().getSupportFragmentManager(), null);
    }

    @Override
    protected void onClick(View v, int id) {
        switch (id) {
            case R.id.iv_clean:
                phoneNumberEdit.setText("");
                break;
            case R.id.tv_no_code:
                startActivity(new Intent(getActivity(), NoVerificationCodeActivity.class));
                break;
            case R.id.tv_psw:
                //密码登录
                loginType = 2;
                tvCodePsw.setVisibility(View.VISIBLE);
                tvForgetPwd.setVisibility(View.INVISIBLE);//忘记密码暂时隐藏
                tvNoCode.setVisibility(View.VISIBLE);
                tvPsw.setVisibility(View.INVISIBLE);
                llCode.setVisibility(View.INVISIBLE);
                llPwd.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_code_psw:
                //验证码登录
                loginType = 1;
                tvCodePsw.setVisibility(View.INVISIBLE);
                tvForgetPwd.setVisibility(View.INVISIBLE);
                tvNoCode.setVisibility(View.VISIBLE);
                tvPsw.setVisibility(View.VISIBLE);
                llCode.setVisibility(View.VISIBLE);
                llPwd.setVisibility(View.INVISIBLE);
                break;

            case R.id.tv_forget_pwd://忘记密码
                getActivity().startActivity(new Intent(getActivity(), ForgetPwdActivity.class)
                        .putExtra("isEdit", "2"));
                break;
            case R.id.tv_send_code:
                String phoneNumber = phoneNumberEdit.getText().toString().trim();
                if (TextUtils.isEmpty(phoneNumberEdit.getText().toString().trim())) {
                    showToast(R.string.seal_login_toast_phone_number_is_null);
                    return;
                }
                if (!RegexUtils.checkMobile(phoneNumber)) {
                    showToast("请输入正确的手机号");
                    return;
                }
                // 请求发送验证码时， 禁止手机号改动和获取验证码的按钮改动
                // 请求完成后在恢复原来状态
                sendCodeBtn.setEnabled(false);
                sendCode("86", phoneNumber/*, imageCode, imageCodeId*/);
                break;
            case R.id.tv_login:
//                if (loginListener != null && !loginListener.beforeLogin()) {
//                    return;
//                }
                String phoneStr = phoneNumberEdit.getText().toString().trim();
                String codeStr = verifyCodeEdit.getText().toString().trim();
                String pwd = inputPwd.getText().toString().trim();
                String countryCodeStr = "86";

                if (loginType == 1) {//验证码
                    if (TextUtils.isEmpty(phoneStr)) {
                        showToast(R.string.seal_login_toast_phone_number_is_null);
                        phoneNumberEdit.setShakeAnimation();
                        break;
                    }
                    if (!RegexUtils.checkMobile(phoneStr)) {
                        showToast("请输入正确的手机号");
                        return;
                    }
                    if (TextUtils.isEmpty(codeStr)) {
                        showToast(R.string.seal_login_toast_code_is_null);
                        verifyCodeEdit.setShakeAnimation();
                        return;
                    }

                    if (!checkbox.isChecked()) {
                        showToast("请阅读并同意用户协议与隐私政策");
                        return;
                    }

                    if (TextUtils.isEmpty(countryCodeStr)) {
                        countryCodeStr = "86";
                    } else if (countryCodeStr.startsWith("+")) {
                        countryCodeStr = countryCodeStr.substring(1);
                    }

                    //                login(countryCodeStr, phoneStr, passwordStr);
                    com.blankj.utilcode.util.SPUtils.getInstance().put("firstOpenApp", false);
                    registerAndLogin(countryCodeStr, phoneStr, codeStr);
                } else {
                    if (TextUtils.isEmpty(phoneStr)) {
                        showToast(R.string.seal_login_toast_phone_number_is_null);
                        phoneNumberEdit.setShakeAnimation();
                        break;
                    }
                    if (!RegexUtils.checkMobile(phoneStr)) {
                        showToast("请输入正确的手机号");
                        return;
                    }
                    if (TextUtils.isEmpty(pwd)) {
                        showToast("密码不能为空");
                        inputPwd.setShakeAnimation();
                        return;
                    }

                    if (!checkbox.isChecked()) {
                        showToast("请阅读并同意用户协议与隐私政策");
                        return;
                    }
                    com.blankj.utilcode.util.SPUtils.getInstance().put("firstOpenApp", false);
                    loginPwd(phoneStr, pwd);
                }

                break;
            case R.id.iv_wechat_login://微信登录
                if (!checkbox.isChecked()) {
                    showToast("请阅读并同意用户协议与隐私政策");
                    return;
                }
                IWXAPI wxapi1 = WXAPIFactory.createWXAPI(getActivity(), Constant.WECHAT_APP_ID, true);
                if (!wxapi1.isWXAppInstalled()) {
                    Log.e("===", "你没有安装微信");
                    com.cxh.rmsq.utils.ToastUtils.showToast("你没有安装微信");
                    return;
                }
                com.blankj.utilcode.util.SPUtils.getInstance().put("firstOpenApp", false);
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo"; // 只能填 snsapi_userinfo
//                req.state = "wechat_sdk_demo_test";
                WXManager.getInstance().getWXAPI().sendReq(req);
                break;
            default:
                break;
        }
    }


    private void initRegistrationTerms() {
        //协议文字及点击事件设置
        TextView registrationTerms = getActivity().findViewById(R.id.tv_service);
        String serviceStr = registrationTerms.getText().toString().trim();
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(serviceStr);
        ClickableSpan clickableSpanOne = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View view) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra(WebViewActivity.PARAMS_TITLE, "用户协议");
                intent.putExtra(WebViewActivity.PARAMS_URL, Constant.userAgreement);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#333333"));
                // 设置下划线 true显示、false不显示
                //paint.setTypeface(Typeface.DEFAULT_BOLD);
                ds.setUnderlineText(false);
            }
        };

        ClickableSpan clickableSpanTwo = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View view) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra(WebViewActivity.PARAMS_TITLE, "隐私政策");
                intent.putExtra(WebViewActivity.PARAMS_URL, Constant.privacyPolicy);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#333333"));
                // 设置下划线 true显示、false不显示
                //paint.setTypeface(Typeface.DEFAULT_BOLD);
                ds.setUnderlineText(false);
            }
        };

//        ClickableSpan clickableSpanThree = new ClickableSpan() {
//            @Override
//            public void onClick(@NonNull View view) {
//                Intent intent = new Intent(getActivity(), WebViewActivity.class);
//                intent.putExtra(WebViewActivity.PARAMS_TITLE, "用户协议");
//                intent.putExtra(WebViewActivity.PARAMS_URL, Constant.userAgreement);
//                startActivity(intent);
//            }
//
//            @Override
//            public void updateDrawState(@NonNull TextPaint ds) {
//                super.updateDrawState(ds);
//                ds.setColor(Color.parseColor("#333333"));
//                // 设置下划线 true显示、false不显示
//                //paint.setTypeface(Typeface.DEFAULT_BOLD);
//                ds.setUnderlineText(false);
//            }
//        };

        stringBuilder.setSpan(clickableSpanOne, 7, 17, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        stringBuilder.setSpan(clickableSpanTwo, 18, 29, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        stringBuilder.setSpan(clickableSpanThree, 28, 42, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 不设置点击不生效
        registrationTerms.setText(stringBuilder);
        registrationTerms.setMovementMethod(LinkMovementMethod.getInstance()); // 不设置 没有点击事件
        registrationTerms.setHighlightColor(Color.TRANSPARENT); // 设置点击后的颜色为透明
    }

    /**
     * 请求发送验证码
     *
     * @param phoneCode   国家地区的手机区号
     * @param phoneNumber 手机号
     */
    private void sendCode(String phoneCode, String phoneNumber/*, String picCode, String picCodeId*/) {
        loginViewModel.sendCode(phoneCode, phoneNumber/*, picCode, picCodeId*/);
    }

    /**
     * 登录到 业务服务器，以获得登录 人脉社区 IM 服务器所必须的 token
     *
     * @param region 国家区号
     * @param phone  电话号/帐号
     * @param pwd    密码
     */
    private void login(String region, String phone, String pwd) {
        loginViewModel.login(region, phone, pwd);
    }

    private void registerAndLogin(String region, String phone, String code) {
        loginViewModel.registerAndLogin(region, phone, code);
    }

    private void loginPwd(String phone, String code) {
        loginViewModel.loginPwd(phone, code);
    }

    private void loginWechat(int type, String openId) {
        loginViewModel.loginWechat(type, openId);
    }

    private void toMain(String userId) {
        Intent intent = new Intent(getActivity(), MainActivity.class);
        intent.putExtra(IntentExtra.USER_ID, userId);
        startActivity(intent);
        getActivity().finish();
    }

    private void toSex() {
        Intent intent = new Intent(getActivity(), SexActivity.class);
//        intent.putExtra(IntentExtra.USER_ID, userId);
        startActivity(intent);
        getActivity().finish();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        verifyCodeEdit = null;
        loginViewModel.stopCodeCountDown();
    }

    public void setLoginListener(OnLoginListener loginListener) {
        this.loginListener = loginListener;
    }

    public interface OnLoginListener {
        boolean beforeLogin();
    }
}
